from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.core.validators import FileExtensionValidator

# 获取用户
OAUser = get_user_model()


class StuffSerializer(serializers.Serializer):
    realname = serializers.CharField(max_length=20, error_messages={"required": "请输入用户名！"})
    email = serializers.EmailField(error_messages={"required": "请输入邮箱！", 'invalid': '请输入正确格式的邮箱！'})
    password = serializers.CharField(max_length=20, error_messages={"required": '请输入密码！'})

    def validate(self, attrs):
        request = self.context['request']
        # 验证当前传入的人员邮箱是否存在于数据库中
        # 验证当前用户是否是部门leader
        email = attrs.get('email')

        # email = attrs.get('email')
        # 邮箱验证
        if OAUser.objects.filter(email=email).exists():
            raise serializers.ValidationError('该邮箱已存在')
        print('leader',request.user.department.leader)
        print('leader uid',request.user.department.leader.uid)
        print('user uid',request.user.uid)
        if request.user.department.leader.uid != request.user.uid:
            raise serializers.ValidationError('非部门leader不能添加员工')
        return attrs

class ActiveStuffSerialize(serializers.Serializer):
    email = serializers.EmailField(error_messages={"required": "请输入邮箱!","invalid": "请输入正确的邮箱"})
    password = serializers.CharField(max_length=20,error_messages={"required": "请输入密码！"})

    def validate(self, attrs):
        email = attrs['email']
        password = attrs['password']
        user = OAUser.objects.filter(email=email).first()
        if not user or not user.check_password(password):
            raise serializers.ValidationError("邮箱或者密码不正确")
        attrs['user'] = user
        return attrs

class StuffUploadSerialize(serializers.Serializer):
    # 校验上传的文件格式是否合法
    file = serializers.FileField(validators=[FileExtensionValidator(['xlsx','xls'])],error_messages={"required": "请上传员工"})

